import pyautogui
import time
from openpyxl import Workbook
from openpyxl.drawing.image import Image as ExcelImage
from PIL import Image

# === 設定 X, Y 的範圍 ===
x_range = range(10, 150,10)   # 示例：10 到 12
y_range = range(10, 110,10)   # 示例：20 到 22

# === 2. 移動並點擊輸入框 ===
pyautogui.moveTo(172, 257, duration=0.5)  # 平滑移動
time.sleep(1)  # 等待一下以防反應慢
pyautogui.click()  # 點擊


# === 建立 Excel 文件 ===
wb = Workbook()
ws = wb.active
ws.title = "坐標與截圖"
ws.append(["X", "Y", "Screenshot"])  # 標題列

# === 遍歷所有 (x, y) 組合 ===
row = 2  # 從第2行開始寫資料
for x in x_range:
    for y in y_range:
        # === 模擬操作與擷取螢幕 ===
        # 延遲讓你切換到你要擷取畫面的應用程式
        xy_str = f"{x}.{y}"
                
        #time.sleep(1)  # 等待一下以防反應慢
        pyautogui.click()  # 點擊
        time.sleep(1)  # 等待一下以防反應慢
        pyautogui.typewrite(xy_str)
        time.sleep(1)
        # === 4.（可選）按 Enter 鍵執行搜尋或確認 ===
        pyautogui.press("enter")
                
        time.sleep(5)
        screenshot = pyautogui.screenshot(region=(7,387,389-7,672-387))

        # 儲存截圖
        img_filename = f"./template/screenshot_{x}_{y}.png"
        screenshot.save(img_filename)

        # === 將數據寫入 Excel ===25.8525.9025.35.30
        
        ws.cell(row=row, column=1, value=x)
        ws.cell(row=row, column=2, value=y)

        # === 插入截圖到 C 列 ===
        img = ExcelImage(img_filename)
        img.width = 150  # 調整圖片大小
        img.height = 100
        ws.add_image(img, f"C{row}")

        row += 1
        #break

# === 儲存 Excel ===
wb.save("xy_screenshots_jnyw.xlsx")
print("完成：已生成 Excel 檔案。")
